#include "SettingUI.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "sys.h"

#define TITLE_HEIGHT 40
#define WIFI_INFO_FMT \
    "*MAC:%s\n"       \
    "*频段:%s\n"    \
    "*比特率:%s\n" \
    "*信号强度:%d%%"

LV_IMG_DECLARE(butterfly)
LV_IMG_DECLARE(poweroff)
LV_IMG_DECLARE(reboot)
LV_IMG_DECLARE(wifi_icon)
LV_IMG_DECLARE(wifi_1)
LV_IMG_DECLARE(wifi_2)
LV_IMG_DECLARE(wifi_3)
LV_IMG_DECLARE(wifi_4)
LV_IMG_DECLARE(wifi_lock)
LV_IMG_DECLARE(wifi_connected)

static lv_ft_info_t font24;
static lv_ft_info_t font30;
static lv_ft_info_t font33;
static lv_ft_info_t font36;

struct Title
{
    lv_obj_t *cont;
    lv_obj_t *label;
    lv_obj_t *backBtn;
};

static void createWiFiPanel(void);
static void createWiFiMessageBox(lv_obj_t *wifi_btn);

static void brightness_slider_event_cb(lv_event_t *e);
static void volume_slider_event_cb(lv_event_t *e);
static void drag_event_handler(lv_event_t *e);
static void poweroff_reboot_btn_event_cb(lv_event_t *e);
static void wifi_btn_event_cb(lv_event_t *e);
static void title_back_event_cb(lv_event_t *e);
static void wifi_list_btn_event_cb(lv_event_t *e);
static void wifi_list_btn_messagebox_top_layer_event_cb(lv_event_t *e);
static void pwd_textarea_event_cb(lv_event_t *e);
static void pwd_btn_event_cb(lv_event_t *e);
static void connect_btn_event_cb(lv_event_t *e);
static void config_btn_event_cb(lv_event_t *e);
static void save_config_msgbox_event_cb(lv_event_t *e);
static void auto_del_obj_timer_cb(lv_timer_t *t);

// gui回调函数集
static SettingUI::Operations uiOpts;

// LCD分辨率
static uint32_t lcdW = 480;
static uint32_t lcdH = 272;

// 背景图片
static lv_obj_t *backImage;

// 顶部标题栏
static Title title;

// 背光滑块小工具
static lv_obj_t *backlightSlider;

// 音量滑块小工具
static lv_obj_t *volumeSlider;

// 退出按钮
static lv_obj_t *exitBtn;

// 关机按钮
static lv_obj_t *poweroffBtn;

// 重启按钮
static lv_obj_t *rebootBtn;

// wifi界面字标题
static lv_obj_t *wifiTitleLabel;

// wifi界面列表list
static lv_obj_t *wifiList;

// 保存已连接的wifi list btn
static lv_obj_t *connectedWiFiBtn;

// wifi连接中提示框容器
static lv_obj_t *connectingCont;

// 网络信息面板标签组
static lv_obj_t *netLabel[7];

// 网络信息面板标签文本头
static const char *netLabelHeader[7] =
    {
        "已连接热点: ",
        "网卡MAC: ",
        "IP地址: ",
        "已接收数据包: ",
        "已发送数据包: ",
        "已接收: ",
        "已发送: ",
};

void SettingUI::create(Operations &opts)
{
    uiOpts = opts;

    // 初始化字体
    font24.name = SystemFontFile;
    font24.weight = 24;
    font24.style = FT_FONT_STYLE_NORMAL;
    font24.mem = nullptr;
    lv_ft_font_init(&font24);

    font30.name = SystemFontFile;
    font30.weight = 30;
    font30.style = FT_FONT_STYLE_NORMAL;
    font30.mem = nullptr;
    lv_ft_font_init(&font30);

    font33.name = SystemFontFile;
    font33.weight = 33;
    font33.style = FT_FONT_STYLE_NORMAL;
    font33.mem = nullptr;
    lv_ft_font_init(&font33);

    font36.name = SystemFontFile;
    font36.weight = 36;
    font36.style = FT_FONT_STYLE_NORMAL;
    font36.mem = nullptr;
    lv_ft_font_init(&font36);

    // 获取显示设备分辨率
    lcdW = lv_disp_get_hor_res(nullptr);
    lcdH = lv_disp_get_ver_res(nullptr);

    // 创建背景图片
    backImage = lv_img_create(lv_scr_act());
    lv_obj_set_size(backImage, lcdW, lcdH);
    lv_img_set_src(backImage, "S:./res/background/settingbg.bin");
    lv_obj_center(backImage);
    lv_obj_clear_flag(backImage, LV_OBJ_FLAG_SCROLLABLE); // 设置不可滚动

    // 创建顶部标题栏
    title.cont = lv_obj_create(backImage);
    lv_obj_set_size(title.cont, lcdW, TITLE_HEIGHT);
    lv_obj_set_style_radius(title.cont, 0, LV_STATE_DEFAULT);                  // 圆角0
    lv_obj_set_style_border_width(title.cont, 0, LV_STATE_DEFAULT);            // 边框宽度0
    lv_obj_set_style_bg_color(title.cont, lv_color_black(), LV_STATE_DEFAULT); // 背景图片
    lv_obj_set_style_bg_opa(title.cont, LV_OPA_70, LV_STATE_DEFAULT);          // 背景透明
    lv_obj_clear_flag(title.cont, LV_OBJ_FLAG_SCROLLABLE);                     // 禁用滚动

    title.label = lv_label_create(title.cont);
    lv_obj_set_height(title.label, TITLE_HEIGHT);
    lv_label_set_text(title.label, "设置");
    lv_obj_set_style_text_color(title.label, lv_color_white(), LV_STATE_DEFAULT);
    lv_obj_set_style_text_font(title.label, font36.font, LV_STATE_DEFAULT);
    lv_obj_set_style_text_opa(title.label, LV_OPA_80, LV_STATE_DEFAULT);
    lv_obj_center(title.label);

    title.backBtn = lv_btn_create(title.cont);
    lv_obj_set_height(title.backBtn, TITLE_HEIGHT);
    lv_obj_align(title.backBtn, LV_ALIGN_LEFT_MID, 0, 0);
    lv_obj_add_flag(title.backBtn, LV_OBJ_FLAG_HIDDEN); // 隐藏
    lv_obj_add_event_cb(title.backBtn, title_back_event_cb, LV_EVENT_SHORT_CLICKED, nullptr);
    lv_obj_t *back_label = lv_label_create(title.backBtn);
    lv_label_set_text(back_label, "返回"); // 返回标签
    lv_obj_set_style_text_color(back_label, lv_color_white(), LV_STATE_DEFAULT);
    lv_obj_set_style_text_font(back_label, font30.font, LV_STATE_DEFAULT);
    lv_obj_set_style_text_opa(back_label, LV_OPA_80, LV_STATE_DEFAULT);
    lv_obj_center(back_label);

    // 创建背光和音量滑块小工具
    lv_obj_t *slider[2];
    const char *title_name[] = {"背光", "音量"};

    for (int i = 0; i < 2; i++)
    {
        slider[i] = lv_slider_create(backImage);
        lv_obj_set_size(slider[i], 400, 15);
        lv_obj_set_pos(slider[i], 100, 100 + i * 60);

        // 创建滑块小工具标题
        lv_obj_t *label = lv_label_create(backImage);                     // 创建滑动条标签
        lv_obj_set_style_text_font(label, font24.font, LV_STATE_DEFAULT); // 设置字体
        lv_label_set_text(label, title_name[i]);
        lv_obj_align_to(label, slider[i], LV_ALIGN_OUT_LEFT_MID, -20, 0);

        // 创建滑块小工具数值标签
        label = lv_label_create(backImage);                               // 创建滑动条标签
        lv_obj_set_style_text_font(label, font24.font, LV_STATE_DEFAULT); // 设置字体
        lv_label_set_text(label, "50%");
        lv_obj_align_to(label, slider[i], LV_ALIGN_OUT_RIGHT_MID, 20, 0);

        lv_obj_set_user_data(slider[i], label); // 绑定对应滑块小工具
    }

    backlightSlider = slider[0];
    volumeSlider = slider[1];

    // 设置滑块小工具范围
    lv_slider_set_range(backlightSlider, 5, 100);
    lv_slider_set_range(volumeSlider, 0, 100);

    // 设置滑块小工具初始值
    if (uiOpts.getBrightness != nullptr)
    {
        int value = uiOpts.getBrightness();
        lv_slider_set_value(backlightSlider, value, LV_ANIM_ON);
        lv_label_set_text_fmt((lv_obj_t *)lv_obj_get_user_data(backlightSlider), "%d%%", value);
    }
    if (uiOpts.getVolume != nullptr)
    {
        int value = uiOpts.getVolume();
        lv_slider_set_value(volumeSlider, value, LV_ANIM_ON);
        lv_label_set_text_fmt((lv_obj_t *)lv_obj_get_user_data(volumeSlider), "%d%%", value);
    }

    // 设置滑块小工具事件回调
    lv_obj_add_event_cb(backlightSlider, brightness_slider_event_cb, LV_EVENT_VALUE_CHANGED, nullptr);
    lv_obj_add_event_cb(volumeSlider, volume_slider_event_cb, LV_EVENT_VALUE_CHANGED, nullptr);

    // 创建关机和重启按钮
    lv_obj_t *btn[2];
    const lv_img_dsc_t *img_dsc[2] = {&poweroff, &reboot};

    for (int i = 0; i < 2; i++)
    {
        btn[i] = lv_obj_create(backImage);
        lv_obj_set_size(btn[i], 132, 132);
        lv_obj_clear_flag(btn[i], LV_OBJ_FLAG_SCROLLABLE); // 禁止滚动
        lv_obj_set_style_bg_color(btn[i], lv_color_white(), LV_STATE_DEFAULT);
        lv_obj_set_style_border_opa(btn[i], LV_OPA_70, LV_STATE_DEFAULT);
        lv_obj_set_style_bg_opa(btn[i], LV_OPA_70, LV_STATE_DEFAULT);
        lv_obj_set_style_radius(btn[i], LV_RADIUS_CIRCLE, LV_STATE_DEFAULT);
        lv_obj_set_style_border_width(btn[i], 5, LV_STATE_DEFAULT); // 边框宽度0
        lv_obj_add_event_cb(btn[i], poweroff_reboot_btn_event_cb, LV_EVENT_SHORT_CLICKED, nullptr);

        lv_obj_t *img = lv_img_create(btn[i]);
        lv_img_set_src(img, img_dsc[i]);
        lv_obj_set_style_img_opa(img, LV_OPA_70, LV_STATE_PRESSED);
        lv_obj_add_flag(img, LV_OBJ_FLAG_CLICKABLE | LV_OBJ_FLAG_EVENT_BUBBLE); // 设置可点击和事件冒泡
        lv_obj_center(img);
    }
    poweroffBtn = btn[0];
    rebootBtn = btn[1];

    // 设置按钮对齐
    lv_obj_align(rebootBtn, LV_ALIGN_BOTTOM_RIGHT, -80, -40);
    lv_obj_align_to(poweroffBtn, rebootBtn, LV_ALIGN_OUT_LEFT_MID, -30, 0);

    // 创建网络信息面板容器
    lv_obj_t *net_cont = lv_obj_create(backImage);
    lv_obj_set_size(net_cont, 500, 300);
    lv_obj_align(net_cont, LV_ALIGN_BOTTOM_LEFT, 50, -40);
    lv_obj_clear_flag(net_cont, LV_OBJ_FLAG_SCROLLABLE);                     // 禁止滚动
    lv_obj_set_style_bg_color(net_cont, lv_color_black(), LV_STATE_DEFAULT); // 容器背景黑色
    lv_obj_set_style_bg_opa(net_cont, LV_OPA_40, LV_STATE_DEFAULT);          // 容器背景透明度
    lv_obj_set_style_border_opa(net_cont, LV_OPA_TRANSP, LV_STATE_DEFAULT);  // 容器边框透明

    // 创建网络信息面板labei
    for (int i = 0; i < 7; i++)
    {
        lv_obj_t *label = lv_label_create(net_cont);
        lv_obj_set_style_text_font(label, font30.font, LV_STATE_DEFAULT);             // 设置字体
        lv_obj_set_style_text_color(label, lv_color_hex(0xcdcdcd), LV_STATE_DEFAULT); // 字体颜色
        lv_label_set_text(label, netLabelHeader[i]);
        netLabel[i] = label;

        if (i != 0)
            lv_obj_align_to(label, netLabel[i - 1], LV_ALIGN_OUT_BOTTOM_LEFT, 0, 0);
        else
            lv_obj_align(label, LV_ALIGN_TOP_LEFT, 10, 0);
    }

    // 创建wifi按钮
    lv_obj_t *wifi_btn_cont = lv_obj_create(net_cont);
    lv_obj_set_size(wifi_btn_cont, 50, 50);
    lv_obj_align(wifi_btn_cont, LV_ALIGN_BOTTOM_RIGHT, 0, 0);
    lv_obj_set_style_bg_color(wifi_btn_cont, lv_color_white(), LV_STATE_PRESSED); // 容器背景白色(按下时)
    lv_obj_set_style_bg_opa(wifi_btn_cont, LV_OPA_40, LV_STATE_PRESSED);          // 容器背景透明度(按下时)
    lv_obj_set_style_bg_opa(wifi_btn_cont, LV_OPA_TRANSP, LV_STATE_DEFAULT);      // 容器背景透明
    lv_obj_set_style_border_opa(wifi_btn_cont, LV_OPA_TRANSP, LV_STATE_DEFAULT);  // 容器边框透明
    lv_obj_clear_flag(wifi_btn_cont, LV_OBJ_FLAG_SCROLLABLE);                     // 设置不可滚动

    lv_obj_t *img = lv_img_create(wifi_btn_cont);
    lv_img_set_src(img, &wifi_icon);
    lv_obj_center(img);
    lv_obj_add_flag(img, LV_OBJ_FLAG_EVENT_BUBBLE | LV_OBJ_FLAG_CLICKABLE); // 事件同时传播到父对象
    lv_obj_add_event_cb(img, wifi_btn_event_cb, LV_EVENT_SHORT_CLICKED, nullptr);
    lv_obj_set_user_data(title.backBtn, img); // 设置用户数据

    // 创建应用程序配置按钮
    lv_obj_t *configBtn = lv_btn_create(backImage);
    lv_obj_set_size(configBtn, 200, 50);
    lv_obj_align(configBtn, LV_ALIGN_TOP_RIGHT, -15, TITLE_HEIGHT + 20);
    lv_obj_add_event_cb(configBtn, config_btn_event_cb, LV_EVENT_SHORT_CLICKED, nullptr);

    lv_obj_t *configBtnLabel = lv_label_create(configBtn);
    lv_label_set_text(configBtnLabel, "应用程序配置"); // 返回标签
    lv_obj_set_style_text_color(configBtnLabel, lv_color_white(), LV_STATE_DEFAULT);
    lv_obj_set_style_text_font(configBtnLabel, font30.font, LV_STATE_DEFAULT);
    lv_obj_set_style_text_opa(configBtnLabel, LV_OPA_80, LV_STATE_DEFAULT);
    lv_obj_center(configBtnLabel);

    // 创建退出按钮
    exitBtn = lv_obj_create(backImage);
    lv_obj_set_size(exitBtn, 70, 70);
    lv_obj_set_pos(exitBtn, 935, 267);
    lv_obj_clear_flag(exitBtn, LV_OBJ_FLAG_SCROLLABLE); // 禁止滚动
    lv_obj_set_style_radius(exitBtn, 35, LV_STATE_DEFAULT);
    lv_obj_set_style_bg_color(exitBtn, lv_color_hex(0xffffff), LV_STATE_DEFAULT);
    lv_obj_set_style_border_opa(exitBtn, LV_OPA_TRANSP, LV_STATE_DEFAULT); // A边框透明
    lv_obj_set_style_bg_opa(exitBtn, LV_OPA_50, LV_STATE_DEFAULT);
    lv_obj_set_style_bg_opa(exitBtn, LV_OPA_90, LV_STATE_PRESSED);

    img = lv_img_create(exitBtn);
    lv_img_set_src(img, &butterfly);
    lv_obj_align(img, LV_ALIGN_CENTER, 0, 0);
    lv_obj_add_flag(img, LV_OBJ_FLAG_EVENT_BUBBLE);

    lv_obj_add_event_cb(exitBtn, drag_event_handler, LV_EVENT_PRESSING, nullptr);
    if (uiOpts.exitCb != nullptr)
        lv_obj_add_event_cb(
            exitBtn,
            [](lv_event_t *e)
            {
                uiOpts.exitCb();
            },
            LV_EVENT_SHORT_CLICKED, nullptr);
}

/**
 *@brief 更新网络信息到UI
 *@param info 网络信息
 */
void SettingUI::updateNetInfo(NetInfo &info)
{
    if (strcmp(info.essid, "null") != 0)
    {
        lv_label_set_text_fmt(netLabel[0], "%s%s", netLabelHeader[0], info.essid);
        lv_obj_set_style_text_color(netLabel[0], lv_color_hex(0x59a3fd), LV_STATE_DEFAULT); // 蓝色系文本
    }
    else
    {
        lv_label_set_text(netLabel[0], "未连接热点!");
        lv_obj_set_style_text_color(netLabel[0], lv_color_hex(0xe1663a), LV_STATE_DEFAULT); // 红色系文本
    }

    lv_label_set_text_fmt(netLabel[1], "%s%s", netLabelHeader[1], info.address);
    lv_label_set_text_fmt(netLabel[2], "%s%s", netLabelHeader[2], info.ipAddr);
    lv_label_set_text_fmt(netLabel[3], "%s%d", netLabelHeader[3], info.rxPackets);
    lv_label_set_text_fmt(netLabel[4], "%s%d", netLabelHeader[4], info.txPackets);
    lv_label_set_text_fmt(netLabel[5], "%s%d kB", netLabelHeader[5], info.rxBytes / 1024);
    lv_label_set_text_fmt(netLabel[6], "%s%d kB", netLabelHeader[6], info.txBytes / 1024);
}

/**
 *@brief 向wifi列表添加一个wifi
 *@param info wifi信息
 */
void SettingUI::addWiFiList(WifiInfo &info)
{
    static const lv_img_dsc_t *wifi_signal_level_img[4] = {&wifi_1, &wifi_2, &wifi_3, &wifi_4};

    if (wifiList == nullptr)
        return;

    WifiInfo *wifi = new WifiInfo;
    memcpy(wifi, &info, sizeof(WifiInfo));

    // 添加一个wifi按钮到list
    lv_obj_t *btn = lv_list_add_btn(wifiList, nullptr, wifi->essid);
    lv_obj_set_style_bg_opa(btn, LV_OPA_TRANSP, LV_STATE_DEFAULT); // 设置背景透明
    lv_obj_set_style_bg_opa(btn, LV_OPA_30, LV_STATE_PRESSED);     // 设置背景透明度(按下时)
    lv_obj_set_style_text_color(btn, lv_color_hex(0xcdcdcd), LV_STATE_DEFAULT);
    lv_obj_set_style_text_font(btn, font33.font, LV_STATE_DEFAULT); // 设置字体
    lv_obj_add_event_cb(btn, wifi_list_btn_event_cb, LV_EVENT_SHORT_CLICKED, nullptr);

    // 创建具有密钥的wifi "锁"图标或者 ""已连接"图标
    lv_obj_t *lock = lv_img_create(btn);
    lv_img_set_src(lock, &wifi_lock);                                // 锁图标
    lv_obj_set_style_img_opa(lock, LV_OPA_TRANSP, LV_STATE_DEFAULT); // 锁图标透明
    lv_obj_align(lock, LV_ALIGN_RIGHT_MID, 0, 0);
    if (info.connected == true)
    {
        lv_img_set_src(lock, &wifi_connected);                          // 已连接图标
        lv_obj_set_style_img_opa(lock, LV_OPA_COVER, LV_STATE_DEFAULT); // 图标不透明
        connectedWiFiBtn = btn;                                         // 保存已连接的wifi btn
    }
    else if (info.encryptionKey == true)
        lv_obj_set_style_img_opa(lock, LV_OPA_COVER, LV_STATE_DEFAULT); // 锁图标不透明

    lv_obj_set_user_data(btn, lock);  // 保存img
    lv_obj_set_user_data(lock, wifi); // 保存wifi信息

    // 创建wifi信号强度图标
    lv_obj_t *signal_level_img = lv_img_create(btn);
    int index = (info.level - 1) / 25;
    lv_img_set_src(signal_level_img, wifi_signal_level_img[index]); // 设置wifi信号强度图标
    lv_obj_align(signal_level_img, LV_ALIGN_RIGHT_MID, 0, 0);
}

void SettingUI::release(void)
{
    lv_obj_del_async(backImage);

    lv_ft_font_destroy(font24.font);
    lv_ft_font_destroy(font30.font);
    lv_ft_font_destroy(font33.font);
    lv_ft_font_destroy(font36.font);
}

/**
 *@brief 创建wifi连接中模态提示框
 */
void SettingUI::connectingContCreate(void)
{
    lv_obj_t *top_layer = lv_layer_top();
    lv_obj_set_style_bg_color(top_layer, lv_palette_main(LV_PALETTE_GREY), LV_STATE_DEFAULT); // top层背景颜色灰色
    lv_obj_set_style_bg_opa(top_layer, LV_OPA_50, LV_STATE_DEFAULT);                          // top层背景透明度

    connectingCont = lv_obj_create(top_layer); // 将容器创建在top层上
    lv_obj_set_size(connectingCont, 300, 100);
    lv_obj_center(connectingCont);
    lv_obj_clear_flag(connectingCont, LV_OBJ_FLAG_SCROLLABLE);                     // 禁止滚动
    lv_obj_set_style_bg_color(connectingCont, lv_color_black(), LV_STATE_DEFAULT); // 容器背景黑色
    lv_obj_set_style_bg_opa(connectingCont, LV_OPA_90, LV_STATE_DEFAULT);          // 容器背景透明度
    lv_obj_set_style_border_opa(connectingCont, LV_OPA_TRANSP, LV_STATE_DEFAULT);  // 容器边框透明

    lv_obj_t *label = lv_label_create(connectingCont);
    lv_obj_set_style_text_font(label, font36.font, LV_STATE_DEFAULT);             // 设置字体
    lv_obj_set_style_text_color(label, lv_color_hex(0x28cbe4), LV_STATE_DEFAULT); // 字体颜色
    lv_label_set_text(label, "正在连接....");
    lv_obj_center(label);

    lv_obj_set_user_data(connectingCont, label);
}

/**
 *@brief 通知UI，连接成功/失败
 *@param status true - 成功    flase - 失败
 */
void SettingUI::setConnectStatus(bool status)
{
    lv_obj_t *label = (lv_obj_t *)lv_obj_get_user_data(connectingCont);

    if (status == true)
        lv_label_set_text(label, "正在获取IP地址....");
    else
        lv_label_set_text(label, "连接失败");
}

/**
 *@brief 通知UI，获取IP地址成功/失败
 *@param status true - 成功    flase - 失败
 */
void SettingUI::setGOTIPStatus(bool status)
{
    lv_obj_t *label = (lv_obj_t *)lv_obj_get_user_data(connectingCont);

    if (status == true)
        lv_label_set_text(label, "连接成功");
    else
        lv_label_set_text(label, "无法获取IP地址");
}

/**
 *@brief 通知UI，连接wifi动作结束
 *@param status true - 连接成功    flase - 连接失败
 */
void SettingUI::setConnectOver(bool status)
{
    // 创建定时器，自动删除对象
    if (connectingCont != nullptr)
    {
        lv_timer_t *timer = lv_timer_create(auto_del_obj_timer_cb, 2000, connectingCont);
        lv_timer_set_repeat_count(timer, 1); // 单次定时器
    }

    lv_event_send(lv_layer_top(), LV_EVENT_CLICKED, nullptr); // 向顶层发送click事件，删除wifi信息面板(如果有)

    lv_obj_t *wifi_btn_img = (lv_obj_t *)lv_obj_get_user_data(connectedWiFiBtn);
    SettingUI::WifiInfo *info = (SettingUI::WifiInfo *)lv_obj_get_user_data(wifi_btn_img);

    if (status == true)
    {
        lv_img_set_src(wifi_btn_img, &wifi_connected); // 已连接图标
        info->connected = true;
    }
    else
    {
        lv_img_set_src(wifi_btn_img, &wifi_lock); // 锁图标
        if (info->encryptionKey == true)
            lv_obj_set_style_img_opa(wifi_btn_img, LV_OPA_COVER, LV_STATE_DEFAULT); // 锁图标不透明
        else
            lv_obj_set_style_img_opa(wifi_btn_img, LV_OPA_TRANSP, LV_STATE_DEFAULT); // 锁图标透明

        info->connected = false;
        connectedWiFiBtn = nullptr;
    }
}

/**
 *@brief 创建wifi面板
 */
static void createWiFiPanel(void)
{
    // 创建子标题
    wifiTitleLabel = lv_label_create(backImage);
    lv_label_set_text(wifiTitleLabel, "WIFI >");
    lv_obj_set_size(wifiTitleLabel, lcdW, 45);
    lv_obj_align_to(wifiTitleLabel, title.cont, LV_ALIGN_OUT_BOTTOM_MID, 0, 0);
    lv_obj_set_style_bg_color(wifiTitleLabel, lv_color_black(), LV_STATE_DEFAULT); // 背景黑色
    lv_obj_set_style_bg_opa(wifiTitleLabel, LV_OPA_COVER, LV_STATE_DEFAULT);       // 设置背景透明度
    lv_obj_set_style_text_color(wifiTitleLabel, lv_color_hex(0xcdcdcd), LV_STATE_DEFAULT);
    lv_obj_set_style_text_font(wifiTitleLabel, font36.font, LV_STATE_DEFAULT); // 设置字体

    // 创建list
    wifiList = lv_list_create(backImage);
    lv_obj_set_size(wifiList, lcdW, lcdH - TITLE_HEIGHT - 45);
    lv_obj_align_to(wifiList, wifiTitleLabel, LV_ALIGN_OUT_BOTTOM_MID, 0, 0);
    lv_obj_set_style_bg_color(wifiList, lv_color_black(), LV_STATE_DEFAULT); // 背景黑色
    lv_obj_set_style_border_opa(wifiList, LV_OPA_TRANSP, LV_STATE_DEFAULT);  // 设置边框透明
    lv_obj_set_style_radius(wifiList, 0, LV_STATE_DEFAULT);                  // 边框圆角为0

    if (uiOpts.wlanScan != nullptr)
        uiOpts.wlanScan();
}

/**
 *@brief 创建某个wifi的模态消息框
 *@param wifi_btn wifi list中的某个btn
 */
static void createWiFiMessageBox(lv_obj_t *wifi_btn)
{
    if (wifi_btn == nullptr)
        return;

    lv_obj_t *btn_img = (lv_obj_t *)lv_obj_get_user_data(wifi_btn);
    SettingUI::WifiInfo *info = (SettingUI::WifiInfo *)lv_obj_get_user_data(btn_img);
    if (info == nullptr)
        return;

    lv_obj_t *top_layer = lv_layer_top();                                                     // 获取top层
    lv_obj_set_style_bg_color(top_layer, lv_palette_main(LV_PALETTE_GREY), LV_STATE_DEFAULT); // top层背景颜色灰色
    lv_obj_set_style_bg_opa(top_layer, LV_OPA_50, LV_STATE_DEFAULT);                          // top层背景透明度
    lv_obj_set_user_data(top_layer, nullptr);

    // 创建模态容器
    lv_obj_add_flag(top_layer, LV_OBJ_FLAG_CLICKABLE); // 设置模态层可点击
    lv_obj_t *cont = lv_obj_create(top_layer);         // 将容器创建在top层上
    lv_obj_set_size(cont, 500, 400);
    lv_obj_center(cont);
    lv_obj_clear_flag(cont, LV_OBJ_FLAG_SCROLLABLE);                     // 禁止滚动
    lv_obj_set_style_bg_color(cont, lv_color_black(), LV_STATE_DEFAULT); // 容器背景黑色
    lv_obj_set_style_bg_opa(cont, LV_OPA_90, LV_STATE_DEFAULT);          // 容器背景透明度
    lv_obj_set_style_border_opa(cont, LV_OPA_TRANSP, LV_STATE_DEFAULT);  // 容器边框透明
    lv_obj_set_user_data(cont, nullptr);

    // 创建窗口标题
    lv_obj_t *title_label = lv_label_create(cont);
    lv_label_set_text_fmt(title_label, "连接到\"%s\"", info->essid);
    lv_obj_set_style_text_font(title_label, font33.font, LV_STATE_DEFAULT);             // 设置字体
    lv_obj_set_style_text_color(title_label, lv_color_hex(0xe6e6e6), LV_STATE_DEFAULT); // 字体颜色
    lv_obj_align(title_label, LV_ALIGN_TOP_LEFT, -10, -20);                             // 标题对齐左上角

    // 创建wifi信息label
    lv_obj_t *info_label = lv_label_create(cont);
    lv_obj_set_style_text_font(info_label, font24.font, LV_STATE_DEFAULT);             // 设置字体
    lv_obj_set_style_text_color(info_label, lv_color_hex(0x8a8a8a), LV_STATE_DEFAULT); // 字体颜色
    lv_label_set_text_fmt(info_label, WIFI_INFO_FMT, info->address, info->freq, info->bitRates, info->level);
    lv_obj_align_to(info_label, title_label, LV_ALIGN_OUT_BOTTOM_LEFT, 10, 0);

    // 创建连接/断开连接按钮
    lv_obj_t *connect_btn = lv_btn_create(cont);
    lv_obj_set_size(connect_btn, 450, 80);
    lv_obj_align(connect_btn, LV_ALIGN_BOTTOM_MID, 0, 0);
    lv_obj_add_event_cb(connect_btn, connect_btn_event_cb, LV_EVENT_SHORT_CLICKED, wifi_btn);

    lv_obj_t *connect_btn_label = lv_label_create(connect_btn);
    lv_obj_set_style_text_font(connect_btn_label, font33.font, LV_STATE_DEFAULT);             // 设置字体
    lv_obj_set_style_text_color(connect_btn_label, lv_color_hex(0xdce2e9), LV_STATE_DEFAULT); // 字体颜色
    lv_label_set_text(connect_btn_label, "连接");
    lv_obj_center(connect_btn_label);
    lv_obj_set_user_data(connect_btn, connect_btn_label);

    if (info->connected == true)
        lv_label_set_text(connect_btn_label, "断开连接");
    else if (info->encryptionKey == true) // 创建wifi密码文本框与密码可视按钮
    {
        lv_obj_t *pwd_textarea = lv_textarea_create(cont);
        lv_obj_set_size(pwd_textarea, 400, 60);
        lv_textarea_set_placeholder_text(pwd_textarea, "请输入密码......"); // 设置占位文本
        lv_textarea_set_password_mode(pwd_textarea, true);                  // 设为密码模式
        lv_textarea_set_password_bullet(pwd_textarea, "*");
        lv_textarea_set_one_line(pwd_textarea, true);                                        // 设置单行模式
        lv_obj_set_style_text_font(pwd_textarea, font33.font, LV_STATE_DEFAULT);             // 设置字体
        lv_obj_set_style_text_color(pwd_textarea, lv_color_hex(0x2c2c2c), LV_STATE_DEFAULT); // 字体颜色
        lv_obj_clear_flag(pwd_textarea, LV_OBJ_FLAG_SCROLLABLE);                             // 禁止滚动
        lv_obj_align_to(pwd_textarea, connect_btn, LV_ALIGN_OUT_TOP_LEFT, 0, -25);
        lv_obj_add_event_cb(pwd_textarea, pwd_textarea_event_cb, LV_EVENT_SHORT_CLICKED, cont); // 设置单击事件回调函数

        if (info->id >= 0)
            lv_textarea_set_text(pwd_textarea, info->psk); // 若是已保存的wifi则自动填入密码

        lv_obj_set_user_data(top_layer, pwd_textarea);

        // 创建密码可视切换按钮
        lv_obj_t *pwd_btn_label = lv_label_create(cont);
        lv_obj_set_style_text_font(pwd_btn_label, &lv_font_montserrat_34, LV_STATE_DEFAULT);  // 设置字体
        lv_obj_set_style_text_color(pwd_btn_label, lv_color_hex(0x8a8a8a), LV_STATE_DEFAULT); // 字体颜色
        lv_label_set_text(pwd_btn_label, LV_SYMBOL_EYE_CLOSE);
        lv_obj_align_to(pwd_btn_label, pwd_textarea, LV_ALIGN_OUT_RIGHT_MID, 12, 0);
        lv_obj_add_flag(pwd_btn_label, LV_OBJ_FLAG_CLICKABLE);

        lv_obj_add_event_cb(pwd_btn_label, pwd_btn_event_cb, LV_EVENT_SHORT_CLICKED, pwd_textarea);
    }

    // 为top layer添加点击事件处理函数
    lv_obj_add_event_cb(top_layer, wifi_list_btn_messagebox_top_layer_event_cb, LV_EVENT_CLICKED, cont);
}

/**
 *@brief 背光滑块小工具事件回调函数
 */
static void brightness_slider_event_cb(lv_event_t *e)
{
    lv_obj_t *slider = lv_event_get_target(e);
    lv_obj_t *label = (lv_obj_t *)lv_obj_get_user_data(slider);

    int value = lv_slider_get_value(slider);

    lv_label_set_text_fmt(label, "%d%%", value);

    if (uiOpts.setBrightness != nullptr)
        uiOpts.setBrightness(value);
}

/**
 *@brief 音量滑块小工具事件回调函数
 */
static void volume_slider_event_cb(lv_event_t *e)
{
    lv_obj_t *slider = lv_event_get_target(e);
    lv_obj_t *label = (lv_obj_t *)lv_obj_get_user_data(slider);

    int value = lv_slider_get_value(slider);

    lv_label_set_text_fmt(label, "%d%%", value);

    if (uiOpts.setVolume != nullptr)
        uiOpts.setVolume(value);
}

/**
 *@brief 长按拖动控件事件函数
 */
static void drag_event_handler(lv_event_t *e)
{
    lv_obj_t *obj = lv_event_get_target(e);

    lv_indev_t *indev = lv_indev_get_act();
    if (indev == nullptr)
        return;

    lv_point_t vect;
    lv_indev_get_vect(indev, &vect);

    lv_coord_t x = lv_obj_get_x(obj) + vect.x;
    lv_coord_t y = lv_obj_get_y(obj) + vect.y;
    lv_obj_set_pos(obj, x, y);
}

/**
 *@brief  关机重启按钮事件回调函数
 */
static void poweroff_reboot_btn_event_cb(lv_event_t *e)
{
    lv_obj_t *btn = lv_event_get_current_target(e);

    if (btn == poweroffBtn)
    {
        if (uiOpts.poweroff != nullptr)
            uiOpts.poweroff();
    }
    else if (btn == rebootBtn)
    {
        if (uiOpts.reboot != nullptr)
            uiOpts.reboot();
    }
}

/**
 *@brief  wifi btn点击事件回调函数
 */
static void wifi_btn_event_cb(lv_event_t *e)
{
    lv_obj_t *btn = lv_event_get_target(e);

    lv_obj_clear_flag(btn, LV_OBJ_FLAG_CHECKABLE);        // 设为不可点击，防止创建多次
    lv_obj_clear_flag(title.backBtn, LV_OBJ_FLAG_HIDDEN); // 显示标题栏返回label
    createWiFiPanel();                                    // 创建wifi面板
}

/**
 *@brief  标题返回labei点击事件回调函数
 */
static void title_back_event_cb(lv_event_t *e)
{
    SettingUI::releaseConfigUI(); // 若configUI不存在,则跳过

    if (wifiTitleLabel != nullptr)
    {
        lv_obj_del(wifiTitleLabel);
        wifiTitleLabel = nullptr;
    }

    if (wifiList != nullptr)
    {
        lv_obj_t *btn = lv_obj_get_child(wifiList, -1);
        while (btn != nullptr)
        {
            lv_obj_t *label = (lv_obj_t *)lv_obj_get_user_data(btn);
            SettingUI::WifiInfo *info = (SettingUI::WifiInfo *)lv_obj_get_user_data(label);
            if (info != nullptr)
                delete info; // 释放wifi信息数据内存

            lv_obj_del(btn);
            btn = lv_obj_get_child(wifiList, -1);
        }

        lv_obj_del(wifiList);
        wifiList = nullptr;
    }

    lv_obj_t *title_back = lv_event_get_target(e);
    lv_obj_t *wifi_btn = (lv_obj_t *)lv_obj_get_user_data(title_back);

    lv_obj_add_flag(title.backBtn, LV_OBJ_FLAG_HIDDEN); // 隐藏标题栏返回label
    lv_obj_clear_flag(wifi_btn, LV_OBJ_FLAG_CHECKABLE); // 设为可点击
}

/**
 *@brief  wifi列表 btn点击事件回调函数
 */
static void wifi_list_btn_event_cb(lv_event_t *e)
{
    lv_obj_t *btn = lv_event_get_target(e);

    createWiFiMessageBox(btn); // 创建一个wifi信息框
}

/**
 *@brief  wifi列表 btn消息框打开时，top layer点击事件回调函数
 */
static void wifi_list_btn_messagebox_top_layer_event_cb(lv_event_t *e)
{
    lv_obj_t *top_layer = lv_event_get_target(e);
    lv_obj_t *cont = (lv_obj_t *)lv_event_get_user_data(e);
    lv_obj_t *keyboard = nullptr;
    lv_obj_t *pwdtextarea = (lv_obj_t *)lv_obj_get_user_data(top_layer);

    if (cont != nullptr)
        keyboard = (lv_obj_t *)lv_obj_get_user_data(cont);

    if (keyboard != nullptr) // 如果键盘已弹出
    {
        lv_obj_del_async(keyboard); // 删除键盘
        lv_obj_set_user_data(cont, nullptr);
        lv_obj_center(cont); // 将窗口归中
        lv_obj_add_event_cb(pwdtextarea, pwd_textarea_event_cb, LV_EVENT_SHORT_CLICKED, cont);
        return;
    }

    if (cont != nullptr)
    {
        lv_obj_del_async(cont); // 删除消息框容器

        lv_obj_remove_event_cb(top_layer, wifi_list_btn_messagebox_top_layer_event_cb); // 移除事件处理函数
        lv_obj_clear_flag(top_layer, LV_OBJ_FLAG_CLICKABLE);
        lv_obj_set_style_bg_opa(top_layer, LV_OPA_TRANSP, LV_STATE_DEFAULT);
        lv_obj_set_user_data(top_layer, nullptr);
    }
}

/**
 *@brief  密码输入框点击事件回调函数
 */
static void pwd_textarea_event_cb(lv_event_t *e)
{
    lv_obj_t *cont = (lv_obj_t *)lv_event_get_user_data(e);

    lv_obj_t *pwd_textarea = lv_event_get_target(e);

    // 创建输入键盘
    lv_obj_t *keyboard = lv_keyboard_create(lv_layer_top());
    lv_obj_set_size(keyboard, lcdW, lcdH / 2);
    lv_keyboard_set_textarea(keyboard, pwd_textarea); // 绑定文本框

    lv_obj_set_user_data(cont, keyboard); // 保存键盘到容器

    lv_obj_align(cont, LV_ALIGN_TOP_MID, 0, 10); // 设置对齐，将窗口往上移动

    lv_obj_remove_event_cb(pwd_textarea, pwd_textarea_event_cb); /// 移除事件回调防止多次创建键盘
}

/**
 *@brief  密码可视按钮点击事件回调函数
 */
static void pwd_btn_event_cb(lv_event_t *e)
{
    lv_obj_t *btn_label = (lv_obj_t *)lv_event_get_target(e);
    lv_obj_t *textarea = (lv_obj_t *)lv_event_get_user_data(e);

    bool pwd_mode = lv_textarea_get_password_mode(textarea);

    if (pwd_mode == true)
    {
        lv_textarea_set_password_mode(textarea, false);   // 切换非密码模式
        lv_label_set_text(btn_label, LV_SYMBOL_EYE_OPEN); // 切换图标表示密码可视
    }
    else
    {
        lv_textarea_set_password_mode(textarea, true);     // 切换密码模式
        lv_label_set_text(btn_label, LV_SYMBOL_EYE_CLOSE); // 切换图标表示密码可视
    }
}

/**
 *@brief  wifi信息面板连接按钮点击事件回调函数
 */
static void connect_btn_event_cb(lv_event_t *e)
{
    lv_obj_t *connect_btn = lv_event_get_target(e);

    lv_obj_t *btn_label = (lv_obj_t *)lv_obj_get_user_data(connect_btn);
    const char *label_text = lv_label_get_text(btn_label);

    lv_obj_t *connect_wifi_btn = (lv_obj_t *)lv_event_get_user_data(e);
    lv_obj_t *connect_wifi_btn_label = (lv_obj_t *)lv_obj_get_user_data(connect_wifi_btn);
    SettingUI::WifiInfo *info = (SettingUI::WifiInfo *)lv_obj_get_user_data(connect_wifi_btn_label);

    if (strcmp(label_text, "连接") == 0)
    {
        if (connectedWiFiBtn != nullptr)
        {
            lv_obj_t *wifi_btn_img = (lv_obj_t *)lv_obj_get_user_data(connectedWiFiBtn);                          // 获取原本的已连接wifi
            SettingUI::WifiInfo *connected_wifi_info = (SettingUI::WifiInfo *)lv_obj_get_user_data(wifi_btn_img); // 获取原本的已连接wifi info
            lv_img_set_src(wifi_btn_img, &wifi_lock);                                                             // 设置锁图标，表示未连接
            lv_obj_set_style_img_opa(wifi_btn_img, LV_OPA_COVER, LV_STATE_DEFAULT);
            connected_wifi_info->connected = false;
        }
        connectedWiFiBtn = connect_wifi_btn; // 保存已连接的wifi list btn

        lv_obj_t *textarea = (lv_obj_t *)lv_obj_get_user_data(lv_layer_top());
        if (textarea != nullptr)
        {
            const char *pwd = lv_textarea_get_text(textarea); // 获取文本框密码
            if (strcmp(info->psk, pwd) != 0)                  // 若已保存的密码与输入密码不相同或者是新的wifi
            {
                strcpy(info->psk, pwd);                           // 以文本框密码为准
                if (uiOpts.changePwd != nullptr && info->id >= 0) // 如果是已保存的wifi
                    uiOpts.changePwd(info->id, info->psk);        // 修改密码
            }
        }

        lv_event_send(lv_layer_top(), LV_EVENT_CLICKED, nullptr); // 向顶层发送click事件，删除wifi信息面板

        if (uiOpts.connectAp != nullptr)
            uiOpts.connectAp(info->id, info->essid, info->psk); // 连接wifi
    }
    else if (strcmp(label_text, "断开连接") == 0)
    {
        if (uiOpts.disconnectAp != nullptr)
            uiOpts.disconnectAp(info->id);
    }
}

/**
 * @brief 配置按钮点击事件回调函数
 */
static void config_btn_event_cb(lv_event_t *e)
{
    lv_obj_t *tabview = SettingUI::createConfigUI(backImage, font33.font);

    lv_obj_t *matrixBtn = lv_tabview_get_tab_btns(tabview);
    lv_obj_set_style_text_font(matrixBtn, font36.font, LV_PART_ITEMS | LV_STATE_DEFAULT); // 设置字体

    lv_obj_clear_flag(title.backBtn, LV_OBJ_FLAG_HIDDEN); // 显示标题栏返回label

    lv_obj_t *btn = lv_btn_create(tabview);
    lv_obj_set_size(btn, 300, 60);
    lv_obj_add_flag(btn, LV_OBJ_FLAG_FLOATING); // 浮空,不受布局影响
    lv_obj_align(btn, LV_ALIGN_BOTTOM_MID, 0, -10);
    lv_obj_add_event_cb(
        btn,
        [](lv_event_t *e)
        {
            static const char *msgboxBtnText[] = {"确定", "取消", nullptr};
            lv_obj_t *tabview = (lv_obj_t *)lv_event_get_user_data(e);
            lv_obj_t *btns = lv_tabview_get_tab_btns(tabview);

            char *text = new char[128];
            const char *pageName = lv_btnmatrix_get_btn_text(btns, lv_tabview_get_tab_act(tabview));
            snprintf(text, 128, "是否保存<%s>配置信息?", pageName);
            lv_obj_t *msgbox = lv_msgbox_create(nullptr, "提示", text, msgboxBtnText, false);
            lv_obj_set_size(msgbox, 400, 220);
            lv_obj_center(msgbox);

            lv_obj_t *msgboxBtns = lv_msgbox_get_btns(msgbox);
            lv_obj_set_size(msgboxBtns, 360, 60);
            lv_obj_set_style_bg_color(msgboxBtns, lv_color_hex(0x00a0ff), LV_STATE_DEFAULT | LV_PART_ITEMS);   // 设置按钮背景颜色
            lv_obj_set_style_text_color(msgboxBtns, lv_color_hex(0xffffff), LV_STATE_DEFAULT | LV_PART_ITEMS); // 设置按钮文字颜色
            lv_obj_align(msgboxBtns, LV_ALIGN_BOTTOM_MID, 0, 0);

            lv_obj_set_style_text_font(lv_msgbox_get_title(msgbox), font33.font, LV_STATE_DEFAULT); // 设置标题字体
            lv_obj_set_style_text_font(lv_msgbox_get_text(msgbox), font24.font, LV_STATE_DEFAULT);  // 设置正文字体
            lv_obj_set_style_text_font(msgboxBtns, font30.font, LV_STATE_DEFAULT | LV_PART_ITEMS);  // 设置按钮字体

            lv_obj_add_event_cb(msgbox, save_config_msgbox_event_cb, LV_EVENT_VALUE_CHANGED, tabview);

            delete text;
        },
        LV_EVENT_CLICKED,
        tabview);

    lv_obj_t *label = lv_label_create(btn);
    lv_label_set_text(label, "保存配置");
    lv_obj_set_style_text_color(label, lv_color_white(), LV_STATE_DEFAULT);
    lv_obj_set_style_text_font(label, font36.font, LV_STATE_DEFAULT);
    lv_obj_set_style_text_opa(label, LV_OPA_80, LV_STATE_DEFAULT);
    lv_obj_center(label);

    if (uiOpts.getConfig != nullptr)
        uiOpts.getConfig();
}

/**
 * @brief 保存配置信息框按钮点击事件回调函数
 */
static void save_config_msgbox_event_cb(lv_event_t *e)
{
    lv_obj_t *msgbox = lv_event_get_current_target(e);

    uint16_t btn_id = lv_msgbox_get_active_btn(msgbox);

    if (btn_id == 0)
    {
        lv_obj_t *tabview = (lv_obj_t *)lv_event_get_user_data(e);
        int act = lv_tabview_get_tab_act(tabview);

        auto itemVector = SettingUI::getPageConfigItemVector(act);

        bool ret = false;
        if(itemVector != nullptr)
        {
            if (uiOpts.saveConfig != nullptr)
                ret = uiOpts.saveConfig(act, *itemVector);

            delete itemVector;
        }

        const char *text = "保存成功!";
        if (ret != true)
            text = "保存失败!";

        lv_obj_t *msgboxBtns = lv_msgbox_get_btns(msgbox);
        lv_obj_t *msgboxText = lv_msgbox_get_text(msgbox);

        static const char *btnText[] = {"确定", nullptr};
        lv_btnmatrix_set_map(msgboxBtns, btnText); // 设置新的按钮文本

        lv_label_set_text(msgboxText, text);

        lv_obj_remove_event_cb(msgbox, save_config_msgbox_event_cb);
        lv_obj_add_event_cb(
            msgbox,
            [](lv_event_t *e)
            {
                lv_obj_t *msgbox = lv_event_get_current_target(e);
                lv_msgbox_close(msgbox); // 关闭信息框
                lv_indev_wait_release(lv_indev_get_act());      // 阻塞输入事件,直到输入设备无输入
            },
            LV_EVENT_VALUE_CHANGED,
            nullptr);
    }
    else
        lv_msgbox_close(msgbox); // 关闭信息框
}

/**
 *@brief  定时删除对象定时器回调函数
 */
static void auto_del_obj_timer_cb(lv_timer_t *t)
{
    lv_obj_t *obj = (lv_obj_t *)t->user_data;

    if (obj == connectingCont)
    {
        lv_obj_set_style_bg_opa(lv_layer_top(), LV_OPA_TRANSP, LV_STATE_DEFAULT); // top层背景透明度
        connectingCont = nullptr;
        lv_obj_del_async(obj);
    }
}